#!/usr/bin/env python
# encoding: utf-8
"""
    @author:水痕
    @time:2018-09-17 16:13:13:47
    @email:332904234@qq.com
    @version:1.0
    @fileName:edit_article.py
    @describe:
"""

from django.shortcuts import render
from django.views.generic import View
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

from article import models
from article.forms import ArticleForms

from django.contrib.auth import get_user_model

# 从系统中获取自己定义的user表
User = get_user_model()


@method_decorator(login_required, name='dispatch')
class EditArticleView(View):
    """
    编辑博客视图类
    """

    def get(self, request, *args, **kwargs):
        article_id = kwargs.get('article_id', None)
        if article_id:
            article = models.ArticleModel.objects.filter(id=article_id).first()
            # 获取文章的类别
            category_list = models.BlogCategoryModel.objects.all()
            type_list = models.TypeCategoryModel.objects.all()
            return render(request, 'edit-article.html', locals())

    def post(self, request, *args, **kwargs):
        article_form = ArticleForms(request.POST)
        article_id = kwargs.get('article_id', None)
        if article_form.is_valid() and request.user.is_authenticated:
            try:
                title = article_form.cleaned_data.get('title', None)
                content = article_form.cleaned_data.get('content', None)
                category = article_form.cleaned_data.get('category', None)
                type = article_form.cleaned_data.get('type', None)
                models.ArticleModel.objects.filter(id=article_id).update(title=title, content=content,
                                                                         category_id=category, type_id=type)
                return JsonResponse({'code': 0, 'message': '成功'})
            except Exception as e:
                print(e)
                return JsonResponse({'code': 1, 'message': e})
        else:
            message = article_form.errors
            return JsonResponse({'code': 1, 'message': message})
